package com.singzi.leetcode.N500;

public class T0475 {
    public static void main(String[] args) {
        int[] houses =  {
                1,5};
        int[] heaters = {10};
        Solution00475 solution00475 = new Solution00475();
        System.out.println(solution00475.findRadius(houses, heaters));
//        System.out.println(solution00475.isHeating(4,houses, heaters));

    }
}
class Solution00475 {
    public int findRadius1(int[] houses, int[] heaters) {

        int rMin = 0;
        int rMax = Math.max(maxNums(houses, true) - maxNums(heaters, false), maxNums(heaters, true)-maxNums(houses, false));
        while (rMin < rMax) {
            int mid = rMin + (rMax - rMin) / 2;
            if (isHeating( mid, houses, heaters)) {
                rMax = mid;
            } else rMin = mid + 1;

        }

        return rMin;
    }

    public boolean isHeating(int radius, int[] houses, int[] heaters ) {

        for (Integer house : houses) {
            boolean isHeat = false;
            for(Integer heater : heaters){
                if(house >= heater - radius && house <= heater+radius){
                    isHeat = true;
                    break;
                }
            }
            if(!isHeat) return false;


        }
        return true;
    }
    public int maxNums(int[] nums, boolean flag){
        int max = nums[0];
        if(flag){
            for (int i = 1; i < nums.length; i++) {
                if(nums[i] > max) max = nums[i];

            }
           return max;
        }
        else {
            for (int i = 1; i < nums.length; i++) {
                if(nums[i] < max) max = nums[i];

            }
            return max;
        }


    }
    public int findRadius(int[] houses, int[] heaters) {

        int rMax = 0;
        for (Integer house:houses){
            int front = -1000000000;
            int rear = 1000000000;
            for (Integer heater:heaters){
                if(heater <=house && heater >= front) front = heater;
                else if(heater >= house && heater <= rear) rear = heater;
            }
            int max = Math.min(rear - house, house - front);
            if(max > rMax)
                rMax = max;
        }


        return rMax;
    }
}